package org.jaronsource.framework.core.web.taglib;

import java.io.File;
import java.io.FileInputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.commons.lang.StringUtils;

public class FileListTag extends TagSupport {

	private static final long serialVersionUID = 3399391125757014516L;

	private String path;

	// private String extensions;

	private String var;

	public String getPath() {
		return path;
	}

	public void setPath( String path ) {
		this.path = path;
	}

	public String getVar() {
		return var;
	}

	public void setVar( String var ) {
		this.var = var;
	}

	@SuppressWarnings( "unchecked" )
	@Override
	public int doStartTag() throws JspException {

		String realPath = pageContext.getServletContext().getRealPath( path );
		String contextPath = pageContext.getServletContext().getContextPath();
		File dir = new File( realPath );
		File[] tempResult = null;
		// if (StringUtils.isNotBlank( extensions )) {
		// String[] extensionArray = StringUtils.split( extensions, "," );
		// FileUtils.
		// }
		if ( dir.exists() && dir.canRead() ) tempResult = dir.listFiles();

		List<FileItem> result = Collections.EMPTY_LIST;
		if ( tempResult != null ) {
			result = new ArrayList<FileItem>();
			for ( File file : tempResult ) {
				FileItem fileItem = new FileItem();
				fileItem.setFileName( file.getName() );
				fileItem.setFilePath( contextPath + path + "/" + file.getName() );
				try {
					fileItem.setFileSize( formetFileSize( new FileInputStream( file ).available() ) );
				}
				catch ( Exception e ) {}
				fileItem.setExt( getFileExt( file.getName() ) );
				result.add( fileItem );
			}

		}

		pageContext.setAttribute( var, result );

		return SKIP_BODY;
	}

	private String getFileExt( String fileName ) {
		int indexOf = fileName.lastIndexOf( "." );
		if ( indexOf != -1 ) { return StringUtils.substring( fileName, indexOf + 1 ); }
		return null;
	}

	private String formetFileSize( long fileS ) {
		DecimalFormat df = new DecimalFormat( "#.00" );
		String fileSizeString = "";
		if ( fileS < 1024 ) {
			fileSizeString = df.format( (double) fileS ) + "B";
		}
		else if ( fileS < 1048576 ) {
			fileSizeString = df.format( (double) fileS / 1024 ) + "K";
		}
		else if ( fileS < 1073741824 ) {
			fileSizeString = df.format( (double) fileS / 1048576 ) + "M";
		}
		else {
			fileSizeString = df.format( (double) fileS / 1073741824 ) + "G";
		}
		return fileSizeString;
	}
}